# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
import json

from .models import User

# Create your views here.

def index(request):
    users = User.objects.all()
    return render(request, 'user/index.html', {'users' : users})

def add(request):
    data = {"userCode":"010","userName":"test","password":"test","sex":"1","email":"test@test.com","age":"1"}
    user = User(**data)
    user.save()
    return HttpResponseRedirect('/user')

def toUpdate(request):
    id = request.GET.get('id')
    try:
        id = int(id)
    except Exception:
        print(id)

    user = User.objects.get(id = id)

    return render(request, 'user/edit.html', {'user': user})


def save(request):
    result = { 'code': 200, 'message': '成功' }
    if request.method == 'POST':
        # 在django1.4中request.raw_post_data 在django1.6中改为了request.body
        # req = json.dump(request.raw_post_data)
        # req = json.dumps(request.body)
        req = json.loads(request.body.decode('utf-8'))
        user = User(**req)
        user.save()
        #do save

    return HttpResponse(json.dumps(result), content_type='application/json')


def delete(request):
    result = {'code': 200, 'message': '删除成功'}
    if request.method == 'GET':
        id = request.GET.get('id')
        try:
            id = int(id)
        except Exception:
            print(id)
        User.objects.get(id=id).delete()

    return HttpResponseRedirect('/user')